package com.example.parkdemo.ping

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.parkdemo.databinding.ItemFooterBinding
import okhttp3.internal.UTC

class FooterAdapter(val retry: () -> Unit) : LoadStateAdapter<FooterAdapter.ViewHolder>() {
    class ViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) {
        val itemFooterBinding = holder.binding as ItemFooterBinding
        when (loadState) {
            is LoadState.NotLoading -> {
                //加载完成，没有其他数据时
                itemFooterBinding.progressBar.visibility = View.GONE
                itemFooterBinding.retryBtn.visibility = View.GONE
            }
            LoadState.Loading -> {
                //读取中
                itemFooterBinding.progressBar.visibility = View.VISIBLE
                itemFooterBinding.retryBtn.visibility = View.VISIBLE
                itemFooterBinding.retryBtn.text = "加载中"
            }
            is LoadState.Error -> {
                //错误
                itemFooterBinding.progressBar.visibility = View.GONE
                itemFooterBinding.retryBtn.visibility = View.GONE
                itemFooterBinding.retryBtn.text = "加载失败，点击重试"
                itemFooterBinding.retryBtn.setOnClickListener {
                    retry()
                }
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder {
        val binding: ItemFooterBinding =
            ItemFooterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }
}